const Router = require('koa-router')
const rateLimit = require('koa-ratelimit')
const svgCaptcha = require('svg-captcha')
const {encrypt, decrypt} = require('../../../core/secret')

const {
    TokenValidator,
    NotEmptyValidator
} = require('../../validators/validator')
const {
    LoginType
} = require('../../lib/enum')
const {
    User
} = require('../../models/user')

const {WXManager} = require('../../services/wx')

const {generateToken} = require('../../../core/util')
const {Auth} = require('../../../middlewares/auth')
const redisClient = require("../../../core/redis")

const CryptoJS = require("crypto-js")


const router = new Router({
    prefix: '/v1/token'
})

// 请求频率限制
const limiter = rateLimit({
    driver: 'memory', // 内存存储
    db: new Map(),
    duration: 60000, // 1分钟
    errorMessage: 'Too many requests, please try again later.',
    id: ctx => ctx.ip,
    headers: {
        remaining: 'Rate-Limit-Remaining',
        reset: 'Rate-Limit-Reset',
        total: 'Rate-Limit-Total'
    },
    max: 10 // 最多10次请求
})


// 验证码生成
router.get('/captcha', limiter, async (ctx) => {
    const captchaData = svgCaptcha.create({
        size: 4,
        ignoreChars: '0o1i',
        noise: 5,
        color: true,
        background: '#ddcc22'
    });
    // 生成一个唯一的键，这里使用简单的时间戳+随机数
    const keys = Date.now() + Math.random().toString(36).substr(2, 9);
    await redisClient.setex(keys, 60, captchaData.text.toLowerCase());
    let captcha = captchaData.data
    let data = {
        keys,
        captcha
    }
    ctx.body = data;
})

// 验证码验证
router.post('/verify-captcha', async (ctx) => {
    const {keys, captcha} = ctx.request.body;

    // 检查是否收到了keys和captcha
    if (!keys || !captcha) {
        ctx.status = 400;
        ctx.body = {error: 'Missing required fields: keys or captcha'};
        return;
    }

    try {
        // 从Redis中获取与keys对应的验证码文本
        const storedCaptcha = await redisClient.get(keys);

        // 检查是否找到了验证码
        if (!storedCaptcha) {
            ctx.status = 200;
            ctx.body = {success: false, message: 'Captcha not found or expired'};
            return;
        }

        // 将提交的captcha转换为小写以匹配存储的格式
        const submittedCaptcha = captcha.toLowerCase();

        // 比较存储的验证码和提交的验证码
        if (storedCaptcha === submittedCaptcha) {
            ctx.status = 200;
            ctx.body = {success: true, message: 'Captcha verified successfully'};
        } else {
            ctx.status = 200;
            ctx.body = {success: false, error: 'Incorrect captcha'};
        }
    } catch (error) {
        // 处理可能的Redis错误
        ctx.status = 500;
        ctx.body = {error: 'Internal server error'};
        console.error('Error verifying captcha:', error);
    }
})

router.post('/', async (ctx) => {
    const v = await new TokenValidator().validate(ctx)
    let data;
    data = await emailLogin(decrypt(v.get('body.account')),
        decrypt(v.get('body.secret')))
    ctx.body = {
        data
    }
})

router.post('/verify', async (ctx) => {
    // token
    const v = await new NotEmptyValidator().validate(ctx)
    const result = Auth.verifyToken(v.get('body.token'))
    ctx.body = {
        is_valid: result
    }
})

//TODO 自动根据user用户-admin字段 判断是否进入管理员界面

async function emailLogin(account, secret) {
    let token = ''
    const user = await
        User.verifyEmailPassword(account, secret)
    if (user.admin >= 2) {
        token = generateToken(user.id, Auth.SUPER_ADMIN)
    } else {
        token = generateToken(user.id, Auth.USER)
    }

    return {
        token: token,
        id: encrypt(user.id),
        name: encrypt(user.nickname),
        admin: encrypt(user.admin)
    }
}

module.exports = router
